package org.xiong.disk.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.xiong.disk.bean.User;
import org.xiong.disk.service.UserService;
import org.xiong.disk.util.HdfsUtil;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired//全自动注入
    UserService userService;

    @Autowired
    HdfsUtil hdfsUtil;

    // 注册
    @PostMapping("/registra")//给予 Post地址
    public String toRegistra(User user, @RequestParam("isPassWord") String isPassWord, Model model) throws Exception {
        if ( (user.getPassWord() != null && !"".equals(user.getPassWord())) &&
                        user.getPassWord().equals(isPassWord) &&
                        !"".equals(user.getPhone()) &&
                        !"".equals(user.getUserName())  &&
                        !"".equals(user.getEmail()) )
        {
            //查询用户信息
            User getUserByPhone = userService.getUserByPhone(user.getPhone());
            if (getUserByPhone == null){
                userService.save(user);
                hdfsUtil.mkdir(user.getPhone());
                model.addAttribute("msg","注册成功!");//注册，检测用户是否存在，是否合法
                return "registration";
            }
//            Msg msg = Msg.fail("用户已经存在");
            model.addAttribute("msg","用户已经存在");
            return "registration";
        }
//        Msg msg = Msg.fail("请输入正确的信息");
        model.addAttribute("msg","请输入正确的信息");
        return "registration";
    }

    @PostMapping("/login")
    public String toLogin(User user,HttpSession session,Model model){
        User userByPhone = userService.getUserByPhone(user.getPhone());
        if (userByPhone == null) {
            model.addAttribute("msg","请注册");
            return "login";
        }
        if (!userByPhone.getPassWord().equals(user.getPassWord())){
            model.addAttribute("msg","请输入正确的密码");
            return "login";
        }
        session.setAttribute("loginUser",userByPhone);
        return "redirect:/index.html";

    }

    @GetMapping("/logOut")
    public String logOut(HttpSession session){
        session.removeAttribute("loginUser");//退回到登录界面
        return "redirect:/";
    }
}